import React, { useState } from "react";
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  TextInput,
  Switch,
  Image,
  Alert,
  Modal,
  ActivityIndicator,
  FlatList,
} from "react-native";
import * as Location from "expo-location";
import * as ImagePicker from "expo-image-picker";
import * as FileSystem from "expo-file-system";
import { Camera } from "expo-camera";
import axios from "axios";
import Mock from "mockjs";
import { router } from "expo-router";
import { useDispatch } from "react-redux";
import { addPost } from "@/store/postSlice";
const OPENCAGE_API_KEY = "9674c1377dec4431b72469cb1e3bc597"; // 替换为你的 OpenCage API Key
const mockData = []; // 模拟存储发布数据的数据库

export default function Publish() {
  const [locationEnabled, setLocationEnabled] = useState(false);
  const [userLocation, setUserLocation] = useState<string | null>(null);
  const [country, setCountry] = useState<string | null>(null);
  const [media, setMedia] = useState([]); // 存储图片或视频
  const [postContent, setPostContent] = useState<string>("");
  const [isModalVisible, setModalVisible] = useState(false); // 控制弹出框
  const [uploading, setUploading] = useState(false); // 上传进度状态
  const dispatch = useDispatch();
  const handleLocationToggle = async () => {
    if (!locationEnabled) {
      try {
        // 请求位置权限
        const { status } = await Location.requestForegroundPermissionsAsync();
        if (status !== "granted") {
          alert("未授予位置权限");
          return;
        }

        // 获取当前位置
        const location = await Location.getCurrentPositionAsync({
          accuracy: Location.Accuracy.High,
        });
        console.log("Location:", location);

        // 使用 OpenCage API 获取地址
        const { latitude, longitude } = location.coords;
        const response = await axios.get(
          `https://api.opencagedata.com/geocode/v1/json?q=${latitude}+${longitude}&key=${OPENCAGE_API_KEY}&language=zh-CN`,
        );

        // 提取国家、省、市
        const components = response.data.results[0]?.components || {};
        const country = components.country || "未知位置";
        const state = components.state || "未知位置";
        const city =
          components.city || components.town || components.village || "未知位置";

        // 格式化为中文字符串
        const formattedAddress = `${country}, ${state}, ${city}`;
        console.log(1111);

        console.log(formattedAddress, "address");
        setCountry(country);
        setUserLocation(formattedAddress);
      } catch (error) {
        console.error("获取位置失败:", error);
        alert("无法获取位置，请确保位置服务已启用并重试。");
      }
    } else {
      // 关闭位置
      setUserLocation(null);
    }
    setLocationEnabled(!locationEnabled);
  };
  // 上传媒体
  const addMedia = async (type: "camera" | "gallery") => {
    const { status } = await (type === "camera"
      ? Camera.requestCameraPermissionsAsync()
      : ImagePicker.requestMediaLibraryPermissionsAsync());

    if (status !== "granted") {
      Alert.alert("未授予权限", "需要访问相机或媒体库的权限。");
      return;
    }

    const result = await (type === "camera"
      ? ImagePicker.launchCameraAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.All,
        allowsEditing: false, // 不裁剪
        quality: 0.8,
      })
      : ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.All,
        allowsEditing: false, // 不裁剪
        quality: 0.8,
      }));

    if (!result.canceled) {
      const newMedia = result.assets[0];

      if (
        newMedia.type === "video" &&
        media.some((item) => item.type === "video")
      ) {
        Alert.alert("错误", "只能上传一个视频。");
        return;
      }
      if (
        newMedia.type === "image" &&
        media.filter((item) => item.type === "image").length >= 9
      ) {
        Alert.alert("错误", "最多只能上传9张图片。");
        return;
      }
      try {
        // 移动文件到永久目录
        const fileName = newMedia.uri.split("/").pop(); // 获取文件名
        const permanentUri = `${FileSystem.documentDirectory}${fileName}`;
        await FileSystem.moveAsync({
          from: newMedia.uri,
          to: permanentUri,
        });
        // 更新媒体列表，使用永久路径
        setMedia((prev) => [
          ...prev,
          { ...newMedia, uri: permanentUri }, // 替换 URI 为永久路径
        ]);
      } catch (error) {
        console.error("文件移动失败:", error);
        Alert.alert("错误", "无法保存文件到永久目录。");
      }

      // setMedia((prev) => [...prev, newMedia]);
    }
    setModalVisible(false); // 关闭弹出框
  };
  // 删除媒体文件
  const removeMedia = (uri: string) => {
    setMedia((prev) => prev.filter((item) => item.uri !== uri));
  };
  // 发布
  const handleCompletePost = async () => {
    if (!postContent || media.length === 0) {
      Alert.alert("发布失败", "请填写完整内容并上传图片或视频");
      return;
    }
    setUploading(true);
    try {
      // 模拟上传逻辑，这里可以用实际的 API 替换
      await new Promise((resolve) => setTimeout(resolve, 2000)); // 模拟 2 秒的上传时间
      const newPost={
        userId:'2',
        content: postContent,
        media: media,
        location: userLocation,
        country: country,
        createTime: Date.now(),
        goods: [],
        comments: []
      }
      // 调用 Redux Action，存储到状态管理中
      dispatch(addPost(newPost));
      Alert.alert("发布成功", "您的动态已成功发布！");
      console.log(media, '图片路径');

      // 清空输入框和图片
      setPostContent("");
      setMedia([]);
      setUserLocation(null);
      setLocationEnabled(false);
      router.push("/square");
    } catch (error) {
      Alert.alert("发布失败", "上传过程中发生错误，请稍后重试。");
    } finally {
      setUploading(false);
    }
  };

  return (
    <View style={styles.container}>
      {/* 顶部导航 */}
      <View style={styles.header}>
        {/* <TouchableOpacity> */}
        <TouchableOpacity onPress={() => router.back()}>
          <Image
            source={require("../../assets/images/left.png")}
            style={styles.backArrow}
          />
        </TouchableOpacity>
        <Text style={styles.title}>发布动态</Text>
        <TouchableOpacity onPress={handleCompletePost}>
          <Text style={styles.completeButton}>完成</Text>
        </TouchableOpacity>
      </View>

      {/* 发布区域 */}
      <TextInput
        placeholder="发布动态，让世界发现你..."
        placeholderTextColor="#999"
        style={styles.textInput}
        multiline
        value={postContent}
        onChangeText={setPostContent}
      />
      {/* 媒体上传 */}
      <View style={styles.mediaContainer}>
        <TouchableOpacity
          style={styles.addMediaButton}
          onPress={() => setModalVisible(true)}
        >
          <Text style={styles.addMediaText}>+</Text>
        </TouchableOpacity>
        <FlatList
          data={media}
          horizontal
          keyExtractor={(item) => item.uri}
          renderItem={({ item }) => (
            <View style={styles.mediaItem}>
              <Image source={{ uri: item.uri }} style={styles.mediaPreview} />
              <TouchableOpacity
                style={styles.deleteButton}
                onPress={() => removeMedia(item.uri)}
              >
                <Text style={styles.deleteText}>×</Text>
              </TouchableOpacity>
            </View>
          )}
        />
      </View>
      {uploading && <ActivityIndicator size="large" color="#00C7B8" />}
      {/* 所在位置 */}
      <View style={styles.locationContainer}>
        <View style={styles.locationRow}>
          <View style={styles.addresss}>
            <Image
              source={require("../../assets/images/address.png")}
              style={styles.backArrow}
            />
            <Text style={styles.locationLabel}>
              {userLocation ? userLocation : "所在位置"}
            </Text>
          </View>
          <Switch
            value={locationEnabled}
            onValueChange={handleLocationToggle}
          />
        </View>
      </View>
      {/* 媒体选择弹出框 */}
      <Modal
        animationType="slide"
        transparent={true}
        visible={isModalVisible}
        onRequestClose={() => setModalVisible(false)}
      >
        <View style={styles.modalOverlay}>
          <View style={styles.modalContent}>
            <TouchableOpacity
              onPress={() => addMedia("camera")}
              style={styles.modalButton}
            >
              <Text style={styles.modalButtonText}>拍照或录像</Text>
            </TouchableOpacity>
            <TouchableOpacity
              onPress={() => addMedia("gallery")}
              style={styles.modalButton}
            >
              <Text style={styles.modalButtonText}>从手机相册选择</Text>
            </TouchableOpacity>
            <TouchableOpacity
              onPress={() => setModalVisible(false)}
              style={styles.modalButton}
            >
              <Text style={styles.modalButtonText}>取消</Text>
            </TouchableOpacity>
          </View>
        </View>
      </Modal>
    </View>
  );
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#ffffff",
    padding: 16,
  },
  header: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    marginBottom: 16,
  },
  backArrow: {
    // fontSize: 24,
    width: 18,
    height: 18,
    color: "#000",
    paddingLeft: 10,
  },
  title: {
    fontSize: 18,
    fontWeight: "bold",
    color: "#000",
  },
  completeButton: {
    fontSize: 16,
    color: "#00C7B8",
  },
  textInput: {
    height: 100,
    borderWidth: 1,
    borderColor: "#e6e6e6",
    borderRadius: 8,
    padding: 10,
    textAlignVertical: "top",
    fontSize: 16,
    color: "#333",
    marginBottom: 16,
  },
  imageUpload: {
    alignItems: "center",
    marginBottom: 16,
  },
  imageUploadBox: {
    width: 100,
    height: 100,
    borderWidth: 1,
    borderColor: "#ddd",
    borderRadius: 8,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#f9f9f9",
  },
  plus: {
    fontSize: 36,
    color: "#ccc",
  },
  selectedImage: {
    width: "100%",
    height: "100%",
    borderRadius: 8,
  },
  warning: {
    fontSize: 12,
    color: "#FF6F61",
    marginTop: 8,
  },
  locationContainer: {
    marginTop: 16,
  },
  locationRow: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
  },
  addresss: {
    width: 300,
    flexDirection: "row",
    flexWrap: "wrap",
  },
  locationLabel: {
    fontSize: 16,
    color: "#333",
    marginLeft: 10,
  },
  modalOverlay: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "rgba(0,0,0,0.5)",
  },
  modalContent: {
    width: 300,
    backgroundColor: "#fff",
    borderRadius: 10,
    padding: 20,
    alignItems: "center",
  },
  modalButton: {
    padding: 10,
    borderBottomWidth: 1,
    borderBottomColor: "#ddd",
    width: "100%",
    alignItems: "center",
  },
  modalButtonText: { fontSize: 16, color: "#007AFF" },
  mediaContainer: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 16,
  },
  mediaItem: { position: "relative", marginRight: 8 },
  mediaPreview: { width: 80, height: 80, borderRadius: 8 },
  deleteButton: {
    position: "absolute",
    top: -8,
    right: -8,
    backgroundColor: "red",
    borderRadius: 8,
    width: 20,
    height: 20,
    justifyContent: "center",
    alignItems: "center",
  },
  deleteText: { color: "#fff", fontSize: 14, fontWeight: "bold" },
  addMediaButton: {
    width: 80,
    height: 80,
    borderWidth: 1,
    borderColor: "#ddd",
    borderRadius: 8,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#f9f9f9",
  },
  addMediaText: { fontSize: 36, color: "#ccc" },
});
